<?php
/*!
 * LostKids PHP Library v0.1 
 * http://huali.li/
 *
 * Copyright 2011, 
 * Written By James Pang
 *  
 * Date: 2011/2/14
 */

/**
 * assemble service instances.
 */
require_once (dirname(__FILE__).'/../configs.php');

class Assembly {

	private static $cache;
	const svc_key_prefix = 'SVC_';
	const plugin_key_prefix = 'SVC_';

	static function init_static() {
		self :: $cache = array ();
	}

	/**
	 * class must have no arg constructor
	 */
	public static function getService($interface, $isCache = false) {
		if ($isCache) {
			$svcKey = Assembly::svc_key_prefix.$interface;
			if (array_key_exists($svcKey, self::$cache))
				return self::$cache[$svcKey];
		}

		global $assembly_services;
		if (array_key_exists($interface, $assembly_services))
			$clzz = $interface.$assembly_services[$interface];
		else
			$clzz = $interface.'Impl';
		$instance = new $clzz(); // autoload

		if ($isCache) {
			self::$cache[$svcKey] = $instance;
		}
		return $instance;

	}

	/**
	 * classes must have no arg constructor
	 * 
	 * @return array[key -> val] plugins
	 */
	public static function getPlugins($interface, $isCache = false) {
        if ($isCache) {
            $svcKey = Assembly::plugin_key_prefix.$interface;
            if (array_key_exists($svcKey, self::$cache))
                return self::$cache[$svcKey];
        }

		$ret = array ();

		global $assembly_plugins;
		$sufixes = $assembly_plugins[$interface];
		if (count($sufixes) > 0) {
			foreach ($sufixes as $surfix) {
				$clzz = $interface . $surfix;
				$ret[$surfix] = new $clzz ();
			}
		}

        if ($isCache) {
            self::$cache[$svcKey] = $ret;
        }
		return $ret;
	}
}Assembly::init_static();
?>
